var Base = gg.module('view.jq.Base');

var View = Base.extend({
    createNode: function(attrs) {
        var el = $('<ul>');
        var self = this;
        el.delegate('li', 'click', function() {
            var target = $(this);
            self.triggerEvent('itemClick', target.index());
        });
        return el;
    },
    addItem: function(index, obj) {
        this.node.append('<li id="' + obj.cid + '">' + obj.cid + JSON.stringify(obj) + '</li>');
    },
    changeItem: function(obj) {
        this.node.find("#" + obj.cid).html(obj.cid + JSON.stringify(obj));
    },
    removeItem: function(obj) {
        this.node.find("#" + obj.cid).remove();
    },
    clearAll: function() {
        this.node.html('');
    }
});

View.metadata = _.extend({}, Base.metadata, {
    itemConfig: {
        defaultValue: {
            classType: 'view.jq.Base',
            html: 'hello world'
        },
        type: 'datatype.Object'
    },
    itemClick: {type: 'Event'},
    data: {
        defaultValue: [],
        type: 'datatype.BaseContainer',
        setter: function(value) {
            //监听数据的改变
            this.stopListening(this._attributes['data']);
            this._attributes['data'] = value;
            this.clearAll();
            value.each(function(v, k) {
                this.addItem(k, v);
            }, this);
            this.listenTo(value, 'add', function(i, obj) {
                this.addItem(i, obj);
            });
            this.listenTo(value, 'remove', function(obj) {
                this.removeItem(obj);
            });
            this.listenTo(value, 'change', function(obj, key, value) {
                this.changeItem(obj);
            });
        }
    }
});

module.exports = View;